package com.isesol.ime.service;

import com.alibaba.fastjson.*;
import com.i5portal.service.interfaces.*;
import com.isesol.arch.common.service.*;
import com.isesol.ime.*;
import com.isesol.ime.dal.mapper.*;
import com.isesol.ime.dal.model.*;
import com.isesol.ime.dto.*;
import com.isesol.ime.service.mqtt.*;
import com.isesol.ime.util.*;
import lombok.extern.slf4j.*;
import org.apache.commons.lang3.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.transaction.support.*;

import javax.annotation.*;
import java.util.*;
import java.util.regex.*;

/**
 * 下指令
 *
 * @author peter zhang
 */
@Component
@Slf4j
public class SendOrderService{

	@Autowired(required = false)
	IVerifyAndSendOrder verifyAndSendOrder;

	@Resource
	TransactionTemplate transactionTemplate;

	@Resource
	SubscriptionMapper subscriptionMapper;

	@Resource
	MessageMapper messageMapper;

	@Resource
	SubscriptionFeedbackMapper subscriptionFeedbackMapper;

	@Resource
	MqttService mqttService;

	public void sendOrderDubbo(OrderDTO orderDTO) throws Exception{

		String result = verifyAndSendOrder.sendOrder(orderDTO.getOrderData(), orderDTO.getCmdId(), orderDTO.getOrderType(),
		                                             orderDTO.getLevel(), orderDTO.getFrequency(), orderDTO.getSwitchs(),
		                                             orderDTO.getDestination());
		Map<String, Object> map     = JSON.parseObject(result, Map.class);
		boolean             success = (boolean) map.get("success");
		if (!success){
			throw new ServiceException(map.get("result").toString());
		} else{
			log.info("sendOrder success,{}", orderDTO);
		}
	}

	public void sendOrderMqtt(OrderDTO orderDTO){

		//todo 前缀的事
		if (!orderDTO.getDestination().startsWith(Constant.PREFIX)){
			orderDTO.setDestination(Constant.PREFIX + orderDTO.getDestination());
		}

		Map map = new HashMap();
		map.put("orderData", orderDTO.getOrderData());
		map.put("cmdId", orderDTO.getCmdId());
		map.put("orderType", orderDTO.getOrderType());
		map.put("level", orderDTO.getLevel());
		map.put("frequence", orderDTO.getFrequency());
		map.put("switchs", orderDTO.getSwitchs());
		map.put("destination", orderDTO.getDestination());

		mqttService.publish("OrderFromThirdPart", JSON.toJSONString(map));
	}

	public void sendOrder(String orderData, String cmdId, String orderType, int level, String frequency, String switchs, String destination)
			throws Exception{

		OrderDTO orderDTO = OrderDTO.builder()
				.orderData(orderData)
				.cmdId(cmdId)
				.orderType(orderType)
				.level(level)
				.frequency(frequency)
				.switchs(switchs)
				.destination(destination)
				.build();

		// send by mqtt
		if (EnvUtil.sendWithMqtt()){

			sendOrderMqtt(orderDTO);

		} else{
			// send by dubbo
			sendOrderDubbo(orderDTO);
		}
	}

	public void sendOrder(String obj) throws Exception{

		if (StringUtils.isBlank(obj)){

			return;
		}

		Map<String, String>    infoMap                = JSON.parseObject(obj, Map.class);
		String                 subId                  = infoMap.get("subId");
		String                 machineId              = infoMap.get("machineId");
		String                 ruleName               = infoMap.get("ruleName");
		String                 rule                   = infoMap.get("rule");
		String                 msgNumber              = infoMap.get("msgNumber");
		SubscriptionFeedbackDO subscriptionFeedbackDO = subscriptionFeedbackMapper.findBySubId(Long.parseLong(subId));
		if (null == subscriptionFeedbackDO){
			return;
		}
		Pattern pattern = Pattern.compile("\\d+");

		int frequency = 0;
		log.info("calc frequency,rule={},machineId={},subscriptionId={}",
		         rule, machineId, subscriptionFeedbackDO.getSubId());
		if (rule.contains("秒")){
			frequency = 1000;
		} else if (rule.contains("分钟")){
			frequency = 1000 * 60;
		} else if (rule.contains("小时")){
			frequency = 1000 * 60 * 60;
		} else if (rule.contains("天")){
			frequency = 1000 * 60 * 60 * 24;
		}

		Matcher matcher = pattern.matcher(rule);

		if (matcher.find()){

			frequency = frequency * Integer.parseInt(matcher.group(0));

		}

		log.info("sendOrder msgNumber={},frequency={},machineId={}",
		         msgNumber, frequency, machineId);
		sendOrder("{}", Constant.FREQUENCY_FEEDBACK + "|" + subId,
		          msgNumber,
		          7,
		          String.valueOf(frequency),
		          "on",
		          machineId);

	}
}
